package com.zhentao.aop;

import com.zhentao.domain.SLogs;
import com.zhentao.service.SLogsService;
import com.zhentao.utils.JwtService;
import org.apache.commons.codec.digest.DigestUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Component
@Aspect
public class AdminAop {


    ThreadLocal<Long> startTime = new ThreadLocal<>();

    @Resource
    private SLogsService logsService;

    @Pointcut("@annotation(com.zhentao.aop.MyLog)")
    public void logPointCut() {
    }


    @Before("logPointCut()")
    public void doBefore(JoinPoint point) {
        startTime.set(System.currentTimeMillis());
    }


    @AfterReturning(value = "logPointCut()", returning = "result")
    public void saveOperLog(JoinPoint joinPoint, Object result) {
        System.out.println("----------------------");
        RequestAttributes att = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = (HttpServletRequest) att.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        String className = joinPoint.getTarget().getClass().getName();
        Method method = signature.getMethod();
        String methodName=className+"."+method.getName();
        Object[] args = joinPoint.getArgs();
        String methodResult="";
        for (Object arg : args) {
            methodResult+=arg.toString()+"----";
        }
        System.out.println(methodResult);
        SLogs logs = new SLogs();
        logs.setMethodname(methodName);
        logs.setMethodresult(result.toString());
        logs.setMethodtype(request.getMethod());
        logs.setTaketime(System.currentTimeMillis()-startTime.get());
        MyLog myLog = method.getAnnotation(MyLog.class);
        if (myLog!=null){
            logs.setTitle(myLog.title());
            logs.setContent(myLog.content());
        }
        String token = request.getHeader("Authorization");
        Map<String, Object> map = JwtService.getClaimsMap(token);
        if (map != null) {
            logs.setName(map.toString().split("nickname=")[1].split(",")[0]);
            logsService.save(logs);
        }
        System.out.println("----------------------");
    }


}
